$(function() {
	
	$.ajax({
		url: "http://120.27.209.174:1010/api/v1/posts_type",
		success(res) {
			console.log(res)
			res.forEach(function(item) {
				$("#type").append(`<option value="${item.type}">${item.text}</option>`)
			})
		}
	})
	
	function serializeObject(form) {
	   var o = {};
	   var a = $(form).serializeArray();
	   $.each(a, function() {
		   if (o[this.name]) {
			   if (!o[this.name].push) {
				   o[this.name] = [o[this.name]];
			   }
			   o[this.name].push(this.value || '');
		   } else {
			   o[this.name] = this.value || '';
		   }
	   });
	   return o;
	};
	
	const E = window.wangEditor
	const editor = new E('#detail')
	// 或者 const editor = new E( document.getElementById('div1') )
	// 配置菜单栏，删减菜单，调整顺序
	// editor.config.menus = [
	// 	'bold',
	// 	'head',
	// 	'link',
	// 	'italic',
	// 	'underline'
	// ]
	editor.config.uploadImgShowBase64 = true
	editor.create()
	
	
	$(".needs-validation").validate({
		// debug: true, //调试模式取消submit的默认提交功能   
		//errorClass: "label.error", //默认为错误的样式类为：error   
		focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
		onkeyup: false,   
		submitHandler: function(form){   //表单提交句柄,为一回调函数，带一个参数：form   
			// 序列化之后的数据
			const data = serializeObject(form)
			data.detail = editor.txt.html()
			// console.log(data)
			$.ajax({
				method: "POST",
				url: "http://120.27.209.174:1010/api/v1/posts",
				data: data,
				success(res) {
					location.href = "./posts.html"
				},
				error(err) {
					alert("发布失败，标题不能重复，或者其他原因，请刷新重试")
				}
			})
		},   
		rules:{
			title: {required:true, rangelength:[ 10, 30]},
			description: {required:true},
			poster: {required:true, url: true},
			author: {required:true},
			type: {required:true},
			detail: {required:true},
		},
		messages:{}
	})
	
	
})


